package com.seari.AlarmSystem.utils;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {
	
	
	//创建ThreadLocal对象，用来存储链接数据
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	
	private static ThreadLocal<Connection> local = new ThreadLocal<Connection>();
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	
	/**
	 * 连接数据库
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException{

		String  url= PropertiesUtil.getProperty("jdbc.properties","db.url");
		String  userName= PropertiesUtil.getProperty("jdbc.properties","db.username");
		String  password= PropertiesUtil.getProperty("jdbc.properties","db.password");
		return DriverManager.getConnection(url,userName,password);
	}
	
	//开启事务
	public static void  startTransaction(){
		Connection con = getCurrentConnection();
		try {
			con.setAutoCommit(false);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//提交事务
	public static void commit(){
		Connection con = getCurrentConnection();
		try {
			con.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void rollback(){
		Connection con = getCurrentConnection();
		try {
			con.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void release(){
		Connection con = getCurrentConnection();
		try {
			//放回连接池
			con.close();
			//将local里面的con给清除
			local.remove();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 获取当前线程，用来进行事务的管理
	 * @return
	 */
	public static Connection getCurrentConnection(){
		Connection con = null;
		try {
			//从local中获取连接
			con = local.get();
			if(con==null){
				//如果本地中没有连接，从数据库连接池获取连接
				con = dataSource.getConnection();
				//将连接存放到local中
				local.set(con);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}
	
	/**
	 * 释放资源
	 * @param con
	 * @param st
	 * @param rs
	 */
	public static void release(Connection con,Statement st,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(st!=null){
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(con!=null){
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
